<?php
namespace plugin\ky_black\app\admin\model;

use support\Model;

class BlackCardSub extends Model
{
    protected $table = 'black_card_sub';
    protected $primaryKey = 'sub_card_id';
    
    protected $fillable = [
        'parent_card_id',
        'sub_card_no',
        'name',
        'mobile',
        'limit_type',
        'fixed_limit',
        'shared_limit',
        'single_limit',
        'day_limit',
        'month_limit',
        'balance',
        'status',
        'remark'
    ];

    protected $casts = [
        'fixed_limit' => 'float',
        'shared_limit' => 'float',
        'single_limit' => 'float',
        'day_limit' => 'float',
        'month_limit' => 'float',
        'balance' => 'float',
        'status' => 'integer'
    ];

    /**
     * 关联主卡
     */
    public function parentCard()
    {
        return $this->belongsTo(BlackCard::class, 'parent_card_id', 'card_id');
    }

    /**
     * 生成子卡号
     */
    public static function generateSubCardNo()
    {
        $prefix = 'SUB';
        $date = date('ymd');
        $random = mt_rand(1000, 9999);
        
        // 生成子卡号
        $subCardNo = $prefix . $date . $random;
        
        // 检查是否已存在
        while (self::where('sub_card_no', $subCardNo)->exists()) {
            $random = mt_rand(1000, 9999);
            $subCardNo = $prefix . $date . $random;
        }
        
        return $subCardNo;
    }

    /**
     * 获取余额分配记录
     */
    public function balanceLogs()
    {
        return $this->hasMany(BlackCardSubBalanceLog::class, 'sub_card_id', 'sub_card_id');
    }
} 